package com.ad2campaign.engine.core.writer;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.CompositeItemWriter;

import com.ad2campaign.engine.core.service.PushNotificationService;
import com.ad2campaign.engine.db.model.NotificationMessage;
import com.ad2campaign.engine.utils.KeystoreHolder;

public class ExtendedJdbcBatchItemWriter extends CompositeItemWriter<NotificationMessage> implements StepExecutionListener
{
	private PushNotificationService pushNotification;
	private ExecutionContext holderMap;
 	private static final Logger LOGGER =  Logger.getLogger(ExtendedJdbcBatchItemWriter.class);
	 
	
	@Override
    public void setDelegates(List<ItemWriter<? super NotificationMessage>> delegates) {
        super.setDelegates(delegates);
    }
	
	public void setPushNotification(PushNotificationService pushNotification){
		this.pushNotification = pushNotification;
	}

	@Override
	public void write(List<? extends NotificationMessage> items)throws Exception 
	{
		LOGGER.debug("Now Proceessing chunk");
		KeystoreHolder keystoreHolder =  (KeystoreHolder)holderMap.get("keystoreHolder");
   		items = this.pushNotification.sendPushNotification(items,keystoreHolder);
		LOGGER.debug("Now sending notification completed");
    	super.write(items);
	}
	

  

	@Override
	public ExitStatus afterStep(StepExecution stepExecution) {
		// TODO Auto-generated method stub
		this.holderMap.remove("keystore");;
		return ExitStatus.COMPLETED;
	 	
	}

	@Override
	public void beforeStep(StepExecution stepExecution) {
		this.holderMap=stepExecution.getJobExecution().getExecutionContext();
		
	}
}
